package com.hins.mq.orderMq;

import com.hins.mq.common.CommUtil;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.Date;
import java.util.List;

public class ProducerA {
    public static void main(String[] args) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        ProducerA producerA = new ProducerA();
        producerA.gosProducer();
    }

    public void gosProducer() throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("pay_finish_group");
        producer.setNamesrvAddr("192.168.0.111:9876");
        producer.start();
        for (int i = 1; i < 4; i++) {
            String tags = "";
            if (i == 1) {
                tags = "rulesProfit";
            }
            if (i == 2) {
                tags = "level";
            }
            if (i == 3) {
                tags = "other";
            }
            System.out.println(tags);
            Message msg = new Message("payFinishTopicTest", tags, CommUtil.ObjectToBytes(i));
            SendResult sendResult = producer.send(msg, new MessageQueueSelector() {

                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
//              Integer id = (Integer) arg;  //根据订单id选择发送queue,不同id不一样的queue,在一样的queue中会保持顺序消费，指定固定队列就可实现全部顺序消费
//              int index = id % mqs.size();
                    return mqs.get(1);
                }
            }, i);

            System.out.println(String.format(new Date() + ", SendResult status:%s, queueId:%d, body:%s", sendResult.getSendStatus(),
                    sendResult.getMessageQueue().getQueueId(), i));
        }
        producer.shutdown();
    }
}
